/**
 * Copyright (c) 2015-2016, smeooncun 失色 (semooncun@foxmail.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lubiaoqing.jsite.interceptor;

import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.lubiaoqing.jsite.model.User;
import com.lubiaoqing.jsite.util.CookieUtils;

public class UserInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		if (c.getSessionAttr("user") != null) {
			inv.invoke();
		} else {
			String userid = CookieUtils.get(c, "user");
			if (StrKit.notBlank(userid)) {
				User user = User.dao.findById(userid);
				if (user != null) {
					user.set("logged", new Date()).update();
					c.setSessionAttr("user", user);
				} else {
					inv.getController().redirect("/admin/user/signin.html");
				}
			} else {
				inv.getController().redirect("/admin/user/signin.html");
			}
		}
	}
}
